package com.wedo.mall.activity.user;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.e.library.activity.EActivity;
import com.e.library.entity.User;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.ESPUtils;
import com.e.library.widget.EImageView;
import com.e.library.widget.ETitleBar;
import com.wedo.mall.R;
import com.wedo.mall.activity.login.Binding;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.util.PhotoUtils;
import com.wedo.mall.util.WUrl;
import com.wedo.mall.util.WUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindDimen;
import butterknife.BindDrawable;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.facebook.Facebook;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.Observable;
import me.iwf.photopicker.PhotoPicker;

import static com.wedo.mall.activity.login.WLogin.USER;

public class PersonalDataActivity extends EActivity {

    @BindView(R.id.title_bar) ETitleBar title_bar;

    @BindView(R.id.eim_portrait) EImageView eim_portrait;
    @BindView(R.id.tv_account) TextView tv_account;
    @BindView(R.id.et_nickname) EditText et_nickname;
    @BindView(R.id.tv_gender) TextView tv_gender;
    @BindView(R.id.rl_gender) RelativeLayout rl_gender;

    @BindView(R.id.rl_facebook) RelativeLayout rl_facebook;
    @BindView(R.id.tv_facebook) TextView tv_facebook;
    @BindView(R.id.rl_wechat) RelativeLayout rl_wechat;
    @BindView(R.id.tv_wechat) TextView tv_wechat;

    @BindDimen(R.dimen.e_padding_mid) int padding;
    @BindDrawable(R.drawable.user_arrow_gray) Drawable drawable_arrow;

    @BindString(R.string.user_male) String male;
    @BindString(R.string.user_female) String female;

    protected User user;
    String img = "";

    private OptionsPickerView pvOptionsGender;
    private ArrayList<String> options1ItemsGender = new ArrayList<>();

    private Binding binding;

    @Override
    protected int layout() {
        return R.layout.activity_personal_data;
    }

    @Override
    protected void onActivityCreated(Bundle state) {
        title_bar.setForwardText(getString(R.string.finish));
        title_bar.showForwordTv();
        title_bar.setForwardTextColor(getResources().getColor(R.color.user_addresslist_font));

        user = WLogin.user();
        Glide.with(this).load(WUrl.url(user.headimgurl)).error(R.drawable.ease_default_avatar).placeholder(R.drawable.ease_default_avatar).diskCacheStrategy(DiskCacheStrategy.ALL).into(eim_portrait);
        tv_account.setText(user.username);
        et_nickname.setText(user.nickname);
        if (TextUtils.equals("0",user.sex)){
            tv_gender.setText(female);
        }else if (TextUtils.equals("1",user.sex)){
            tv_gender.setText(male);
        }else {
            tv_gender.setText(male);
        }

        options1ItemsGender.add(0,female);
        options1ItemsGender.add(1,male);


        binding = new Binding(user).listener(new Binding.BindingListener() {
            @Override
            public void loading() {
                PersonalDataActivity.this.loading();
            }

            @Override
            public void successful(String platform) {
                if(TextUtils.equals(Facebook.NAME,platform)) {
                    isBinding(true,rl_facebook,tv_facebook);
                }else if(TextUtils.equals(Wechat.NAME,platform)) {
                    isBinding(true,rl_wechat,tv_wechat);
                }
                dismiss();
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });

        drawable_arrow.setBounds(0,0,drawable_arrow.getMinimumWidth(),drawable_arrow.getMinimumHeight());
        tv_facebook.setCompoundDrawables(null,null,drawable_arrow,null);
        isBinding(user.isBindingWechat(),rl_wechat,tv_wechat);
        isBinding(user.isBindingFacebook(),rl_facebook,tv_facebook);

    }

    private void isBinding(boolean binding,RelativeLayout rl,TextView tv){
        if(binding) {
            rl.setClickable(false);
            tv.setSelected(true);
            tv.setText(getResources().getString(R.string.auth_binding));
            tv.setPadding(0,0,padding,0);
            tv.setCompoundDrawables(null,null,null,null);
        }else {
            rl.setClickable(true);
            tv.setSelected(false);
            tv.setText(getResources().getString(R.string.auth_un_binding));
            tv.setPadding(0,0,0,0);
            tv.setCompoundDrawables(null,null,drawable_arrow,null);
        }
    }

    @OnClick({R.id.rl_facebook,R.id.rl_wechat})
    protected void onBindingClick(View view){
        switch (view.getId()){
            case R.id.rl_facebook:
                binding.facebook(this);
                break;
            case R.id.rl_wechat:
                binding.wechat(this);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode !=RESULT_OK || data == null) return;

        switch (requestCode){
            case PhotoPicker.REQUEST_CODE:
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                img = PhotoUtils.rotate(this,photos.get(0));//修复三星手机图片旋转的bug
                Glide.with(this).fromFile().load(new File(img)).into(eim_portrait);
                break;
        }
    }

    private void upload(){
        String imgStr = WUtils.toBase64(img);
        Observable<EResponse> observable = api().upload(imgStr,"User");
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                img = response.string("image");
                UpdateUser();
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }

    private void UpdateUser(){
        Map<String,String> params = new HashMap<>(3);
        if(TextUtils.isEmpty(img)){

            params.put("nickname",et_nickname.getText().toString());
            params.put("sex",user.sex);
        }else{
            params.put("nickname",et_nickname.getText().toString());
            params.put("sex",user.sex);
            params.put("headimgurl",img);
        }

        Observable<EResponse> observable = EClient.with().api().post(EApi.USER_UPDATEUSER,params);
        EClient.with().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {

                getUserInfo();
            }

            @Override
            public void failure(String msg) {
                PersonalDataActivity.this.dismiss(msg);
            }
        });
    }

    @OnClick(R.id.et_nickname)
    protected void onEditNicknameClick(){
        et_nickname.setCursorVisible(true);
    }

    @OnClick(R.id.tv_forward)
    protected void onUpdateUserClick(){
        String nickname = et_nickname.getText().toString().trim();
        if(TextUtils.isEmpty(nickname)){
            toast(getString(R.string.user_namenull));
        }else if(img == "" || img.equals(null)){
            loading();
            UpdateUser();
        }else{
            loading();
            upload();
        }
    }

    @OnClick(R.id.rl_gender)
    protected void onGenderClick(){

        int gender = 1;
        if (!TextUtils.isEmpty(user.sex)){
            gender = Integer.parseInt(user.sex);
        }
        //条件选择器
        pvOptionsGender = new  OptionsPickerView.Builder(PersonalDataActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                //返回的分别是三个级别的选中位置
                user.sex = String.valueOf(options1);
                tv_gender.setText(options1ItemsGender.get(options1));

            }
        })
                .setTitleText(getResources().getString(R.string.gender))//标题
                .setTitleColor(getResources().getColor(R.color.e_purple))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.e_purple))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.e_purple))//取消按钮文字颜色
                .setSelectOptions(gender)
                .build();
        pvOptionsGender.setPicker(options1ItemsGender);
        pvOptionsGender.show();
    }

    @OnClick(R.id.rl_modifypassword)
    protected void onModifyPasswordClick(){
        toActivity(ChangePasswordActivity.class);
    }

    @OnClick(R.id.rl_portrait)
    protected void onPortraitClick(){
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(true)
                .setShowGif(false)
                .setPreviewEnabled(true)
                .start(PersonalDataActivity.this, PhotoPicker.REQUEST_CODE);
    }

    /**
     * 获取个人信息
     */
    private void getUserInfo(){
        EClient.with().post(EApi.USER_INFO, new EObserver() {
            @Override
            public void successful(EResponse response) {
                User user = response.object("list",User.class);
                ESPUtils.setString(PersonalDataActivity.this,USER,user.toString());
                dismiss();
                defaultFinish();
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }

        });
    }
}
